package com.exercises;

import com.exercises.common.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Exercise993 {

    public boolean isCousins(TreeNode root, int x, int y) {
        return dfs(Arrays.asList(root), x, y);
    }

    public boolean dfs(List<TreeNode> root, int x, int y) {
        if (root.size() == 0) return false;
        List<TreeNode> chlids = new ArrayList<>();
        int count = 0;
        for (TreeNode r : root) {
            if (r.val == x || r.val == y) {
                count++;
            }

            if (r.left != null && r.right != null) {
                boolean a = Math.max(x, y) == Math.max(r.left.val, r.right.val);
                boolean b = Math.min(x, y) == Math.min(r.left.val, r.right.val);
                if (a && b) {
                    return false;
                }
            }
            if (r.left != null) chlids.add(r.left);
            if (r.right != null) chlids.add(r.right);


        }
        if (count == 2) return true;
        return dfs(chlids, x, y);

    }
}

